<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <!-- <el-form-item label="商户id" prop="merchantId">
        <el-input
          v-model="queryParams.merchantId"
          placeholder="请输入商户id"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="店铺id" prop="storeId">
        <el-input
          v-model="queryParams.storeId"
          placeholder="请输入店铺id"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="券组id" prop="groupId">
        <el-input
          v-model="queryParams.groupId"
          placeholder="请输入券组id"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <el-form-item label="券名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入券名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!-- <el-form-item label="是否允许转赠" prop="isGive">
        <el-input
          v-model="queryParams.isGive"
          placeholder="请输入是否允许转赠"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="适用会员等级" prop="gradeIds">
        <el-input
          v-model="queryParams.gradeIds"
          placeholder="请输入适用会员等级"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="获得卡券所消耗积分" prop="point">
        <el-input
          v-model="queryParams.point"
          placeholder="请输入获得卡券所消耗积分"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="适用商品：allGoods、parkGoods" prop="applyGoods">
        <el-input
          v-model="queryParams.applyGoods"
          placeholder="请输入适用商品：allGoods、parkGoods"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="领取码" prop="receiveCode">
        <el-input
          v-model="queryParams.receiveCode"
          placeholder="请输入领取码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="使用专项" prop="userFor">
        <el-input
          v-model="queryParams.userFor"
          placeholder="请输入使用专项"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="有效期，单位：天" prop="expireTime">
        <el-input
          v-model="queryParams.expireTime"
          placeholder="请输入有效期，单位：天"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="开始有效期" prop="beginTime">
        <el-date-picker clearable
          v-model="queryParams.beginTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择开始有效期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="结束有效期" prop="endTime">
        <el-date-picker clearable
          v-model="queryParams.endTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择结束有效期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="面额" prop="amount">
        <el-input
          v-model="queryParams.amount"
          placeholder="请输入面额"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="发放方式" prop="sendWay">
        <el-input
          v-model="queryParams.sendWay"
          placeholder="请输入发放方式"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="每次发放数量" prop="sendNum">
        <el-input
          v-model="queryParams.sendNum"
          placeholder="请输入每次发放数量"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="发行数量" prop="total">
        <el-input
          v-model="queryParams.total"
          placeholder="请输入发行数量"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="每人拥有数量限制" prop="limitNum">
        <el-input
          v-model="queryParams.limitNum"
          placeholder="请输入每人拥有数量限制"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="所属店铺id,逗号隔开" prop="storeIds">
        <el-input
          v-model="queryParams.storeIds"
          placeholder="请输入所属店铺id,逗号隔开"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="最后操作人" prop="operator">
        <el-input
          v-model="queryParams.operator"
          placeholder="请输入最后操作人"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['backendApi:coupon:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <!-- <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['backendApi:coupon:edit']"
        >修改</el-button> -->
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['backendApi:coupon:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['backendApi:coupon:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="couponList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="卡类型" align="center" prop="type">
        <template slot-scope="scope" >
          <dict-tag :options="dict.type.tm_coupon_type" :value="scope.row.type" />
        </template>
      </el-table-column>
      <el-table-column label="卡项名称" align="center" prop="name" />
      <el-table-column label="卡项价格" align="center" prop="amount" :formatter="addUnit2"/>
      <el-table-column label="可用余额/次数" align="center" prop="usableMoney" :formatter="addUnit"/>
      <el-table-column label="后台备注" align="center" prop="remarks" />
      


      <!-- <el-table-column label="自增id" align="center" prop="id" />
      <el-table-column label="卡类型" align="center" prop="type" />
      <el-table-column label="包含项目/服务次数" align="center" prop="applyGoods" />
      <el-table-column label="商户id" align="center" prop="merchantId" />
      <el-table-column label="店铺id" align="center" prop="storeId" />
      <el-table-column label="券组id" align="center" prop="groupId" />
      <el-table-column label="是否允许转赠" align="center" prop="isGive" />
      <el-table-column label="适用会员等级" align="center" prop="gradeIds" />
      <el-table-column label="获得卡券所消耗积分" align="center" prop="point" />
      <el-table-column label="领取码" align="center" prop="receiveCode" />
      <el-table-column label="使用专项" align="center" prop="userFor" />
      <el-table-column label="过期类型" align="center" prop="expireType" />
      <el-table-column label="有效期，单位：天" align="center" prop="expireTime" />
      <el-table-column label="开始有效期" align="center" prop="beginTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.beginTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结束有效期" align="center" prop="endTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.endTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="发放方式" align="center" prop="sendWay" />
      <el-table-column label="每次发放数量" align="center" prop="sendNum" />
      <el-table-column label="发行数量" align="center" prop="total" />
      <el-table-column label="每人拥有数量限制" align="center" prop="limitNum" />
      <el-table-column label="不可用日期，逗号隔开。周末：weekend；其他：2019-01-02_2019-02-09" align="center" prop="exceptTime" />
      <el-table-column label="所属店铺id,逗号隔开" align="center" prop="storeIds" />
      <el-table-column label="描述信息" align="center" prop="description" />
      <el-table-column label="效果图片" align="center" prop="image" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.image" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="后台备注" align="center" prop="remarks" />
      <el-table-column label="获取券的规则" align="center" prop="inRule" />
      <el-table-column label="核销券的规则" align="center" prop="outRule" />
      <el-table-column label="最后操作人" align="center" prop="operator" />
      <el-table-column label="A：正常；D：删除" align="center" prop="status" /> -->

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <!-- <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['backendApi:coupon:edit']"
          >修改</el-button> -->
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['backendApi:coupon:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改卡券信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>
        
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <!-- <el-form-item label="卡类型" prop="type">
          <el-radio-group v-model="form.type" placeholder="请选择卡类型" >
            <el-radio
                v-for="dict in dict.type.tm_coupon_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
                
            />
          </el-radio-group>
        </el-form-item> -->
        <el-form-item label="卡类型" prop="type" >
        <el-radio-group v-model="form.type" @change="handleRadioChange">
            <el-radio v-for="item in dict.type.tm_coupon_type" :key="item.value" :label="item.value">
                {{ item.label }}
            </el-radio>
        </el-radio-group>
        </el-form-item>

        <!-- <el-form-item label="卡类型" prop="type" >
          <el-radio-group v-model="form.type" @change="handleRadioChange">
            <el-radio
                v-for="item in dict.type.tm_coupon_type"
                :key="item.value"
                :label="item.value"
                :value="item.label"
            />
          </el-radio-group>
        </el-form-item>
        <el-form-item label="卡类型2" prop="type">
          <el-select v-model="form.type" @change="handleRadioChange">
            <el-option
                v-for="dict in dict.type.tm_coupon_type"
                :key="dict.value"
                :label="dict.value"
                :value="dict.label"
            />
          </el-select>
        </el-form-item> -->
        <el-row :gutter="20">
            <el-col :span="10">
                <el-form-item label="卡项名称" prop="name">
                    <el-input v-model="form.name" placeholder="如:10次xxx卡" />
                </el-form-item>
            </el-col>
            <el-col :span="10">
                <el-form-item label="充值金额" prop="amount">
                    <el-input v-model="form.amount" placeholder="请输充值金额" @input="handleInput"/>
                </el-form-item>
            </el-col>
        </el-row>
        <el-row :gutter="20">
            <el-col :span="10">
                <el-form-item label="赠送金额" prop="giveMoney" v-if="form.type === 'P'">
                    <el-input v-model="form.giveMoney" placeholder="请输入赠送金额" @input="handleInput"/>
                    </el-form-item>
            </el-col>
            <el-col :span="10">
                <el-form-item label="可用金额" prop="usableMoney" v-if="form.type === 'P'">
                    <el-input v-model="form.usableMoney" placeholder="自动计算" disabled/>
                </el-form-item>
            </el-col>
        </el-row>
        <el-row :gutter="20">
            <el-col :span="10">
                <el-form-item label="次数" prop="usableTime" v-if="form.type === 'T'">
                    <el-input v-model="form.usableTime" placeholder="请输入次数"/>
                </el-form-item>
            </el-col>
            <el-col :span="10">
                <el-form-item label="说明" prop="remarks">
                    <el-input v-model="form.remarks"  placeholder="请输入内容" />
                </el-form-item>
            </el-col>
        </el-row>
        
        <!-- <el-form-item label="显示顺序" prop="orderNum">
          <el-input v-model="form.orderNum" placeholder="请输入显示顺序" />
        </el-form-item>
        <el-form-item label="包含项目" prop="applyGoods">
                    <el-input v-model="form.applyGoods" placeholder="请输入适用商品" />
                </el-form-item>
        <el-form-item label="券组id" prop="groupId">
          <el-input v-model="form.groupId" placeholder="请输入券组id" />
        </el-form-item>
         <el-form-item label="商户id" prop="merchantId">
            <el-input v-model="form.merchantId" placeholder="请输入商户id" />
        </el-form-item>
        <el-form-item label="店铺id" prop="storeId">
            <el-input v-model="form.storeId" placeholder="请输入店铺id" />
        </el-form-item>
        <el-form-item label="是否允许转赠" prop="isGive">
          <el-input v-model="form.isGive" placeholder="请输入是否允许转赠" />
        </el-form-item>
        <el-form-item label="适用会员等级" prop="gradeIds">
          <el-input v-model="form.gradeIds" placeholder="请输入适用会员等级" />
        </el-form-item>
        <el-form-item label="获得卡券所消耗积分" prop="point">
          <el-input v-model="form.point" placeholder="请输入获得卡券所消耗积分" />
        </el-form-item>
        <el-form-item label="领取码" prop="receiveCode">
          <el-input v-model="form.receiveCode" placeholder="请输入领取码" />
        </el-form-item>
        <el-form-item label="使用专项" prop="userFor">
          <el-input v-model="form.userFor" placeholder="请输入使用专项" />
        </el-form-item>
        <el-form-item label="有效期，单位：天" prop="expireTime">
          <el-input v-model="form.expireTime" placeholder="请输入有效期，单位：天" />
        </el-form-item>
        <el-form-item label="开始有效期" prop="beginTime">
          <el-date-picker clearable
            v-model="form.beginTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择开始有效期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结束有效期" prop="endTime">
          <el-date-picker clearable
            v-model="form.endTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择结束有效期">
          </el-date-picker>
        </el-form-item>
        
        <el-form-item label="发放方式" prop="sendWay">
          <el-input v-model="form.sendWay" placeholder="请输入发放方式" />
        </el-form-item>
        <el-form-item label="每次发放数量" prop="sendNum">
          <el-input v-model="form.sendNum" placeholder="请输入每次发放数量" />
        </el-form-item>
        <el-form-item label="发行数量" prop="total">
          <el-input v-model="form.total" placeholder="请输入发行数量" />
        </el-form-item>
        <el-form-item label="每人拥有数量限制" prop="limitNum">
          <el-input v-model="form.limitNum" placeholder="请输入每人拥有数量限制" />
        </el-form-item>
        <el-form-item label="不可用日期，逗号隔开。周末：weekend；其他：2019-01-02_2019-02-09" prop="exceptTime">
          <el-input v-model="form.exceptTime" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="所属店铺id,逗号隔开" prop="storeIds">
          <el-input v-model="form.storeIds" placeholder="请输入所属店铺id,逗号隔开" />
        </el-form-item>
        <el-form-item label="描述信息" prop="description">
          <el-input v-model="form.description" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="效果图片" prop="image">
          <image-upload v-model="form.image"/>
        </el-form-item>
        
        <el-form-item label="获取券的规则" prop="inRule">
          <el-input v-model="form.inRule" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="核销券的规则" prop="outRule">
          <el-input v-model="form.outRule" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="最后操作人" prop="operator">
          <el-input v-model="form.operator" placeholder="请输入最后操作人" />
        </el-form-item> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listCoupon, getCoupon, delCoupon, addCoupon, updateCoupon } from "@/api/backendApi/coupon";
import Decimal from "@/api/common/decimal.js";

export default {
  name: "Coupon",
  dicts: ['tm_coupon_type'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 卡券信息表格数据
      couponList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        merchantId: null,
        storeId: null,
        groupId: null,
        type: null,
        name: null,
        isGive: null,
        gradeIds: null,
        point: null,
        applyGoods: null,
        receiveCode: null,
        userFor: null,
        expireType: null,
        expireTime: null,
        beginTime: null,
        endTime: null,
        amount: null,
        sendWay: null,
        sendNum: null,
        total: null,
        limitNum: null,
        exceptTime: null,
        storeIds: null,
        description: null,
        image: null,
        remarks: null,
        inRule: null,
        outRule: null,
        operator: null,
        status: null,
        giveMoney: null,
        usableMoney: null,
        usableTime: null,
        orderNum: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        groupId: [
          { required: true, message: "券组id不能为空", trigger: "blur" }
        ],
        name: [
          { required: true, message: "券名称不能为空", trigger: "blur" }
        ],
        usableTime: [
            { required: true, message: "次数不能为空", trigger: "blur" },
          {
            pattern: /^\d{1,5}$/,
            message: '数字长度不超过5位的整数',
            trigger: 'blur'
          }
        ],
        amount: [
            { required: true, message: "充值金额不能为空", trigger: "blur" },
          {
            pattern: /^\d{1,7}(\.\d{1,2})?$/,
            message: '数字长度不超过7位，小数位数不超过2位',
            trigger: 'blur'
          }
        ],
        giveMoney: [
          {
            pattern: /^\d{1,7}(\.\d{1,2})?$/,
            message: '数字长度不超过7位，小数位数不超过2位',
            trigger: 'blur'
          }
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    // 设置数字单位
    addUnit2(row, column, cellValue) {
            return parseFloat(cellValue).toFixed(2)+ "元";
            // return cellValue + "元";
    },
    addUnit(row, column, cellValue) {
        if(row.type === 'T'){
            return cellValue + "次";
        }else{
            return parseFloat(cellValue).toFixed(2)+ "元";
            // return cellValue + "元";
        }
    },
    /** 储值卡根据充值金额和赠送金额计算可用金额 */
    handleInput(event) {
        if(this.form.type === 'P'){
            this.form.usableMoney='';
            const num1 = this.form.amount ? new Decimal(this.form.amount): new Decimal(0);
            const num2 = this.form.giveMoney ? new Decimal(this.form.giveMoney): new Decimal(0);
            const result = num1.add(num2).toNumber();
            this.form.usableMoney = result;
        }
    },
    /** 切换选项清空数据 */
     handleRadioChange(newValue) {
    //   console.log('用户选择了新的选项:', newValue);
      this.reset();
      if (newValue === 'P') {
        this.form.type='P'
      }else{
        this.form.type='T'
      }
    },
    /** 查询卡券信息列表 */
    getList() {
      this.loading = true;
      listCoupon(this.queryParams).then(response => {
        this.couponList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        merchantId: null,
        storeId: null,
        groupId: null,
        type: 'T',
        name: null,
        isGive: null,
        gradeIds: null,
        point: null,
        applyGoods: null,
        receiveCode: null,
        userFor: null,
        expireType: null,
        expireTime: null,
        beginTime: null,
        endTime: null,
        amount: null,
        sendWay: null,
        sendNum: null,
        total: null,
        limitNum: null,
        exceptTime: null,
        storeIds: null,
        description: null,
        image: null,
        remarks: null,
        inRule: null,
        outRule: null,
        createTime: null,
        updateTime: null,
        operator: null,
        status: null,
        giveMoney: null,
        usableMoney: null,
        usableTime: null,
        orderNum: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加卡券信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getCoupon(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改卡券信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateCoupon(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addCoupon(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除卡项名称为"' + row.name + '"的数据项？').then(function() {
        return delCoupon(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('backendApi/coupon/export', {
        ...this.queryParams
      }, `coupon_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
